<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb5">
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['cms:user:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['cms:user:export']"
        >导出</el-button>
      </el-col>
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px" class="el-form-search">
                        <el-form-item label="用户名称" prop="userName" class="el-form-search-item">
                            <el-input
                                    v-model="queryParams.userName"
                                    placeholder="请输入用户名称"
                                    clearable
                                    size="mini"
                                    @keyup.enter.native="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="用户等级" prop="userLevel" class="el-form-search-item">
                            <el-input
                                    v-model="queryParams.userLevel"
                                    placeholder="请输入用户等级"
                                    clearable
                                    size="mini"
                                    @keyup.enter.native="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="注册时间" prop="registerDate" class="el-form-search-item">
                            <el-date-picker clearable size="mini"
                                            v-model="queryParams.registerDate"
                                            type="date"
                                            value-format="yyyy-MM-dd"
                                            placeholder="选择注册时间">
                            </el-date-picker>
                        </el-form-item>
            <el-form-item class="el-form-search-item">
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
    </el-row>

    <el-table :height="tableHeight" v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="50" align="center">
            <template scope="scope">
          <span>{{
            (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1
          }}</span>
            </template>
        </el-table-column>
      <el-table-column label="用户名称" align="center" prop="userName" />
      <el-table-column label="用户密码" align="center" prop="userPassWord" />
      <el-table-column label="用户等级" align="center" prop="userLevel" >
        <template slot-scope="scope">
          <el-select v-model="scope.row.userLevel" @change="updateLevel(scope.row)" class="custom-select">
            <el-option label="0" value="0"></el-option>
            <el-option label="1" value="1"></el-option>
            <el-option label="2" value="2"></el-option>
            <el-option label="3" value="3"></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="用户积分" align="center" prop="userIntegral" />
      <el-table-column label="用户状态" align="center" prop="userStatus" >
        <template slot-scope="scope">
          <el-switch v-model="scope.row.userStatus"
          :active-value='0'
          :inactive-value="1"
          @change="changeStatus(scope.row)">
        </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="注册时间" align="center" prop="registerDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.registerDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后登录时间" align="center" prop="loginDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.loginDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['cms:user:edit']"
          >调整积分</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal="false" v-dialogDrag>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="操作类型" prop="categoryStatus">
          <el-radio-group v-model="optType">
            <el-radio :label="1">增加</el-radio>
            <el-radio :label="0">减少</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="积分" prop="score">
          <el-input v-model="score" placeholder="请输入调整的积分" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style>
.custom-select .el-select__input,
.custom-select .el-input .el-input__inner {
  text-align: center;
}
</style>

<script>
import { listUser, getUser, delUser, addUser, updateUser,updateUserByStatus } from "@/api/cms/user";
import { addRecord } from "@/api/cms/record";

export default {
  name: "User",
  data() {
    return {
      optType: 1,
      score: 0,
      // 表格高度
      tableHeight: document.documentElement.clientHeight - 180,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户管理表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: "register_date",
        isAsc: "desc",
        userName: null,
        userLevel: null,
        userStatus: null,
        registerDate: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" }
        ],
        userPassWord: [
          { required: true, message: "用户密码不能为空", trigger: "blur" }
        ],
        userLevel: [
          { required: true, message: "用户等级不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询用户管理列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userName: null,
        userPassWord: null,
        userLevel: null,
        userIntegral: null,
        userStatus: 0,
        registerDate: null,
        loginDate: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getUser(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改积分";
      });
    },
    changeStatus(row){
      let obj ={};
      obj.id = row.id;
      obj.userStatus = row.userStatus?1:0;
      updateUser(obj).then(response=>{
        this.$modal.msgSuccess("修改成功");
      })
    },
    updateLevel(row){
      debugger
      let obj ={};
      obj.id = row.id;
      obj.userLevel = row.userLevel
      updateUser(obj).then(response=>{
        this.$modal.msgSuccess("修改成功");
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            var obj = {};
            obj.id = this.form.id;
            if(this.optType==1){
              obj.userIntegral = parseInt(this.form.userIntegral)+parseInt(this.score);
            }else{
              obj.userIntegral = (parseInt(this.form.userIntegral)-parseInt(this.score))<0?0:(parseInt(this.form.userIntegral)-parseInt(this.score));
            }

            updateUser(obj).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.integralRecord();
              this.open = false;
              this.getList();
              this.optType = 1;
              this.score = 0;
            });
          } else {
            addUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    integralRecord(){
      debugger
      let obj = {};
      obj.userId=this.form.id;
      obj.userName = this.form.userName;
      obj.integral = this.score;
      obj.type = this.optType==1?1:2;
      obj.recordDesc="手动调整";
      addRecord(obj).then(response=>{
        console.log("添加记录成功")
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除记录？').then(function() {
        return delUser(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('cms/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
